<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table'
import TableAction from '#/components/TableAction/index.vue'
import { useTableCURD } from '#/hooks/useTableList'
import { Page } from '@vben/common-ui'
import { $t } from '@vben/locales'
import { ref, onUnmounted } from 'vue'
import {
    Button,
    Switch,
    Row,
    Col,
    FormItem,
    Input,
    UploadDragger,
    message,
    Popconfirm,
    Modal
} from 'ant-design-vue'
import { columns } from './data/table'
import type { TableListItem } from './use/api'
import { PageApi } from './use/api'
const isComplete = ref<boolean>(true)
var timer = ref<any>(null)
var formValues = ref({ batchNumber: '20253230170902' })
var formObj = ref({
    regNum: '', //每次注册数量
    intervalSeconds: '' //时间间隔
})
var workId: any = ref()
var workInfo = ref<any>({})
const gridOptions: VxeGridProps<any> = {
    columns,
    proxyConfig: {
        ajax: {
            query: async ({ page }) => {
                const res = await PageApi.getPageList({
                    ...formValues.value,
                    limit: page.pageSize,
                    page: page.currentPage
                })
                return {
                    items: res.records,
                    total: res.total
                }
            }
        }
    },
    height: 500,
    scrollY: {
        enabled: true,
        gt: 0
    },
    showOverflow: true
}

/**
 * 表格配置
 */
const {
    Grid,
    reload,
    FormModal,
    edit: handleEdit,
    handleSuccess,
    viewDetail: handleDetail
} = useTableCURD<TableListItem>({
    isHideForm: true,
    gridOptions,
    updateStatusApi: PageApi.statuseEdit
})

/**
 * table 操作
 * @param record
 */
function getActions(record: TableListItem) {
    const arr: any[] = [
        {
            icon: 'ant-design:eye-outlined',
            tooltip: $t('common.details'),
            onClick: () => {
                handleDetail(record)
            }
        },
        {
            icon: 'clarity:note-edit-line',
            tooltip: $t('common.import'),
            onClick: () => {
                handleEdit(record)
            }
        }
    ]

    return arr
}
// 开始工作
const handleStart = async () => {
    // 验证注册数量是否为有效的正整数
    const regNum = Number(formObj.value.regNum)
    if (!formObj.value.regNum || isNaN(regNum) || regNum <= 0 || !Number.isInteger(regNum)) {
        message.error('请输入有效的注册数量')
        return
    }

    // 验证时间间隔是否为有效的正数
    const intervalSeconds = Number(formObj.value.intervalSeconds)
    if (
        !formObj.value.intervalSeconds ||
        isNaN(intervalSeconds) ||
        intervalSeconds <= 0 ||
        !Number.isInteger(intervalSeconds)
    ) {
        message.error('请输入有效的时间间隔')
        return
    }
    // 拿工作id
    const res = await PageApi.start({
        ...formValues.value,
        ...formObj.value
    })
    workId.value = res
    // 存储工作流id，用于结束工作，以及回到当前页面查询进度
    if (workId.value) {
        localStorage.setItem(
            '注册workId',
            JSON.stringify({
                workId: workId.value,
                formObj: formObj.value
            })
        )
        message.warning('开始工作...')
        handleWorkProgress(workId.value)
    }
}
// 封装工作查询功能
const handleWorkProgress = async (workId: any) => {
    const res = await PageApi.readWorkProgress(workId)
    isComplete.value = res.isComplete
    workInfo.value = res
    // 轮询
    timer.value = setInterval(async () => {
        if (isComplete.value) {
            localStorage.removeItem('注册workId')
            return false
        }
        const res = await PageApi.readWorkProgress(workId)
        isComplete.value = res.isComplete
        workInfo.value = res
        if (isComplete.value) {
            message.success('工作完成')
            localStorage.removeItem('注册workId')
            clearInterval(timer.value)
        }
    }, 2000)
}
if (!workId.value && localStorage.getItem('注册workId')) {
    message.warning('继续查询工作进度...')
    workId.value = JSON.parse(localStorage.getItem('注册workId') || '{}').workId
    formObj.value = JSON.parse(localStorage.getItem('注册workId') || '{}').formObj
    handleWorkProgress(workId.value)
}
// 结束工作
const handleEnd = async () => {
    if (isComplete.value) {
        message.error('工作已完成，不能重复结束')
        return
    }
    const res = await PageApi.endWork(workId.value)
    if (res) {
        clearInterval(timer.value)
        isComplete.value = true
        message.success('结束成功')
        localStorage.removeItem('注册workId')
    }
}
// 清空数据
const handleClear = async () => {
    if (!isComplete.value) {
        message.error('工作未完成，不能清空数据')
        return
    }
    const res = await PageApi.clear(formValues.value.batchNumber)
    if (res) {
        formValues.value.batchNumber = ''
        reload()
        message.success('清空成功')
    }
}
const handleExport = async (type: number) => {
    await PageApi.export(type)
    message.success('导出成功')
}
// 在组件卸载时清除定时器
onUnmounted(() => {
    if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
    }
})

const titleText = formValues.value.batchNumber
    ? '确定清空当前批次的数据吗？'
    : '确定清空所有的数据吗？'
const open = ref(false)
const fileList = ref([])
const objFile: any = ref({})
const logObj: any = ref({})
// 上传文件
const handleUpload = async (file: any, fileList: any) => {
    logObj.value = {}
    fileList = fileList
    objFile.value = file
    return false
}
async function handleOk() {
    if (objFile.value?.name) {
        const res = await PageApi.upload({ file: objFile.value })
        logObj.value = res
        if (res.batchNumber) {
            message.success('上传成功')
            formValues.value.batchNumber = res.batchNumber
            reload()
        } else {
            message.error('上传失败')
        }
    }
}
</script>

<template>
    <Page>
        <Grid>
            <template #toolbar-tools>
                <view class="flex gap-2">
                    <Button @click="open = true">导入邮箱</Button>
                    <Button type="primary" @click="handleExport(0)"> 导出异常邮箱 </Button>
                    <Popconfirm :title="titleText" @confirm="handleClear">
                        <Button danger> 清空数据 </Button>
                    </Popconfirm>
                </view>
            </template>
            <template #status="{ row }">
                <Switch
                    :checked="row.status"
                    :checked-value="1"
                    :un-checked-value="0"
                    :checked-children="$t('options.status.children.normal')"
                    :un-checked-children="$t('options.status.children.disabled')"
                />
            </template>
            <template #action="{ row }">
                <TableAction :actions="getActions(row)" />
            </template>
        </Grid>
        <Row class="form-item-spacing bg-card pl-3">
            <Col span="12" class="pb-10">
                <Row>
                    <Col span="8">
                        <FormItem label="注册成功" name="customerName">
                            {{ workInfo.successNum }}个
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="注册失败" name="contactPhone">
                            {{ workInfo.failureNum }}个
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="8">
                        <FormItem label="每次注册" name="contactPhone">
                            <Input placeholder="个" v-model:value="formObj.regNum" />
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="时间间隔" name="customerName">
                            <Input placeholder="秒" v-model:value="formObj.intervalSeconds" />
                        </FormItem>
                    </Col>
                </Row>
                <Button :loading="!isComplete" type="primary" class="mr-2" @click="handleStart">
                    开始工作
                </Button>
                <Button danger @click="handleEnd"> 结束工作 </Button>
            </Col>
            <Col
                span="12"
                class="pb-10"
                style="
                    min-height: 400px;
                    max-height: 400px;
                    overflow-y: auto;
                    background-color: black;
                "
            >
                <Button style="color: chartreuse" type="text" :loading="true" v-if="!isComplete"
                    >读取中...</Button
                >
                <p
                    class="pt-3"
                    v-for="item in workInfo.logList ? [...workInfo.logList].sort().reverse() : []"
                    :key="item"
                >
                    <span style="color: chartreuse; padding: 10px">{{ item }}</span>
                </p>
            </Col>
        </Row>
        <Modal v-model:open="open" title="邮箱导入" @ok="handleOk">
            <a
                style="color: #278df2; display: inline-block"
                class="pb-3"
                href="http://34.29.16.102:9000/stars-co-dev/login_and_register_import.xlsx"
                download="账号导入模版.xlsx"
                >下载模版</a
            >
            <UploadDragger
                v-model:fileList="fileList"
                name="file"
                :multiple="true"
                :maxCount="1"
                :directory="false"
                :accept="'.xls,.xlsx'"
                :beforeUpload="handleUpload"
            >
                <p class="ant-upload-drag-icon">
                    <inbox-outlined></inbox-outlined>
                </p>
                <p class="ant-upload-text">上传导入文件</p>
                <p class="ant-upload-hint">文件格式xls，xlsx</p>
            </UploadDragger>
            <div>
                <div class="text-red-500" v-if="logObj.failureNum">
                    导入失败数量"{{ logObj.failureNum }}"原因：
                </div>
                <ul>
                    <li v-for="item in logObj.failureLogList" :key="item.username">{{ item }}</li>
                </ul>
                <div style="color: greenyellow" v-if="logObj.successNum">
                    导入成功数量{{ logObj.successNum }}
                </div>
                <ul>
                    <li v-for="item in logObj.successLogList" :key="item.username">{{ item }}</li>
                </ul>
            </div>
        </Modal>
        <FormModal @success="handleSuccess" />
    </Page>
</template>
<style scoped lang="scss">
.form-item-spacing .ant-form-item {
    margin-right: 16px;
}
</style>
